package face.pay.cpn;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;
import com.github.wxpay.sdk.exception.SignException;
import face.pay.cpn.utils.request.RequestParam;
import face.pay.cpn.utils.response.ErrorCode;
import face.pay.cpn.utils.response.ResponseMessage;
import face.pay.dao.CpnMarketInfoDao;
import face.pay.entity.CpnMarketInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public abstract class AbstractApiService {

    @Autowired
    protected CpnMarketInfoDao cpnMarketInfoDao;

    private static final String defaultKey="0123456789987654";

    public ResponseMessage doApi(String json){

        ResponseMessage responseMessage = null;
        String key = defaultKey;
        RequestParam requestParam = null;
        String marketCode = null;
        try{
            log.error("解析参数");
            requestParam = JSON.parseObject(json, RequestParam.class);
            marketCode  = requestParam.getMarketCode();
            if(StringUtils.isBlank(marketCode)){
                responseMessage = ResponseMessage.createFail(ErrorCode.PARAM_FAIL_CODE,"marketCode 未指定");
            }
        }catch (Exception e){
            log.error("参数解析错误",e);
            responseMessage =  ResponseMessage.createFail(ErrorCode.PARAM_FAIL_CODE,"参数解析失败");
        }



        log.error("查找投放平台信息");
        CpnMarketInfo cpnMarketInfo  = this.cpnMarketInfoDao.queryCpnMarketInfo(new CpnMarketInfo(marketCode));

        if(cpnMarketInfo!=null){

            String sign = requestParam.getSign();
            Map<String,String> data = requestParam.getData();


            /**
             * 如果没有设置key 去默认
             */
            if(StringUtils.isNotBlank(cpnMarketInfo.getSecurity_key())){
                key =cpnMarketInfo.getSecurity_key();
            };
            Boolean isValid = false;
            try {
                 isValid = WXPayUtil.isSignatureValid(data, key, sign);
            }catch (Exception e){
                log.error("验证签名失败",e);
            }

            if(isValid){
                try{
                    responseMessage =   doService(cpnMarketInfo,requestParam);
                }catch (Exception e){
                    log.error("执行业务异常",e);
                    responseMessage  = ResponseMessage.createFail(ErrorCode.FAIL_CODE,"未知异常");
                }
            }else {
                responseMessage =  ResponseMessage.createSignFail();
            }
        }else{
            log.error("不存在的 marketCode");
            responseMessage =  ResponseMessage.createFail(ErrorCode.AUTH_ERROR,"不存在的 marketCode");

        }
        String nonceStr = WXPayUtil.generateNonceStr();
        Map<String,String > signMap =  new HashMap<>();
        signMap.put("nonceStr",nonceStr);
        signMap.put("marketCode",marketCode);

        try {
            String resultSign = WXPayUtil.generateSignature(signMap,key);
            responseMessage.setSign(resultSign);
            responseMessage.setNonceStr(nonceStr);
        }catch (Exception e){
            log.error("加签失败",e);
            /**
             * 加签失败
             */
            responseMessage  = ResponseMessage.createFail(ErrorCode.SIGN_FAIL_CODE,"加签失败");
        }


        return  responseMessage;
    }

    public abstract ResponseMessage  doService(CpnMarketInfo cpnMarketInfo, RequestParam requestParam) throws Exception;

}
